package cn.honqun.tinycms.config;

import cn.honqun.tinycms.common.json.DateDeserializer;
import cn.honqun.tinycms.common.json.LocalDateTimeDeserializer;
import cn.honqun.tinycms.common.json.LongDeserializer;
import cn.honqun.tinycms.common.json.LongSerializer;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.TimeZone;

/**
 * 初始化JacksonJson，Spring MVC使用此ObjectMapper
 */
@Configuration
@Slf4j
public class JacksonConfig {

    private static final ObjectMapper objectMapper;

    static {
        //将Long解析为String，以防Javascript丢失精度
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, new LongSerializer());
        simpleModule.addDeserializer(Long.class, new LongDeserializer());

        // 日期反序列化，Date类型自动识别各种格式
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addDeserializer(Date.class, new DateDeserializer());
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());

        objectMapper = new ObjectMapper();

        objectMapper.registerModule(simpleModule).registerModule(javaTimeModule);
        // 忽略未知字段
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //忽略为空的字段
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //时区
        objectMapper.setTimeZone(TimeZone.getDefault());
    }

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        log.info("初始化ObjectMapper");
        return objectMapper;
    }
}
